package com.example.useaar

import android.os.Bundle
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import kotlinx.android.synthetic.main.an.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.an)
//        A.show()
        launchFromGlobalScope()
    }

    private fun launchFromGlobalScope() {
        println("launchFromGlobalScope " + Thread.currentThread().name)
        launch {
            println("launch " + Thread.currentThread().name)
            withContext(Dispatchers.IO) {
                println("withContext IO " + Thread.currentThread().name)
                var data = getClient().getDatas().await()
                withContext(Dispatchers.Main) {
                    println("withContext Main " + Thread.currentThread().name)
                    if (data?.data != null && data.data.size > 0) {
                        tv.text = data.data[0].name
                    }
                }
            }
        }
    }

    fun getClient(): GitHubAPI {
        val BASE_URL = "https://wanandroid.com/"
        val reqApi by lazy {
            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .build()
            return@lazy retrofit.create(GitHubAPI::class.java)
        }
        return reqApi
    }
}
